package com.jy.adscm.operation.mscyb.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.base.bean.JyGoods;
import com.jy.adscm.operation.cg.bean.CgBom;
import com.jy.adscm.operation.cg.bean.CgMaterial;
import com.jy.adscm.operation.cg.mapper.mysql.CgBomMapper;
import com.jy.adscm.operation.cg.mapper.mysql.CgMaterialMapper;
import com.jy.adscm.operation.mscyb.bean.*;
import com.jy.adscm.operation.mscyb.mapper.mysql.*;
import com.jy.adscm.operation.mscyb.service.JqbzMaterialListService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.operation.mscyb.service.JqylMaterialService;
import com.jy.adscm.operation.purchase.bean.Purchasebom;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-05-25
 */
@Service
public class JqbzMaterialListServiceImpl extends ServiceImpl<JqbzMaterialListMapper, JqbzMaterialList> implements JqbzMaterialListService {
     @Autowired
     JqylMaterialService jqylMaterialService;
     @Autowired
     JqylMaterialMapper jqylMaterialMapper;
     @Autowired
     CgMaterialMapper cgMaterialMapper;
     @Autowired
    JqylMaterialdetailMapper jqylMaterialdetailMapper;
     @Autowired
    JqbzMaterialMapper jqbzMaterialMapper;
     @Autowired
    JyUserMapper jyUserMapper;
     @Autowired
    JqbzMaterialListCheckMapper jqbzMaterialListCheckMapper;
     @Autowired
     JqbzPartsassemblyMapper jqbzPartsassemblyMapper;
     @Autowired
     JqylSettingMaterialCheckMapper jqylSettingMaterialCheckMapper;

     @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertJqbzMaterialList(JqbzMaterialList jqbzMaterialList, Token token)throws AdscmSystemException {

         JqbzMaterial jqbzMaterial1 = jqbzMaterialMapper.selectById(jqbzMaterialList.getPid());
         JqbzPartsassembly jqbzPartsassembly1 = jqbzPartsassemblyMapper.selectById(jqbzMaterial1.getTid());
         if (jqbzPartsassembly1.getTaskstate()==0){
             throw new AdscmSystemException("该状态不能领取物料");
         }

         float temp=  jqbzMaterialList.getNum();

         int num= (int)temp ;
         boolean isInt=true;
         if (temp==num){

         }else {
             num=1;
             isInt=false;
         }

         for (int i = 0; i < num; i++) {

             if (isInt){
                 jqbzMaterialList.setNum(1f);
             }else {
                 jqbzMaterialList.setNum(temp);
             }
             //根据这个查询原来库存中是否还存在余料
             if (AdscmBaseUtils.getInstance().isNotEmpty(jqbzMaterialList.getName(), null)) {

                 //修改库存  减去库存  num相反数
                 JqylMaterial jqylMaterial = jqylMaterialService.updateJqylMaterialyValue(jqbzMaterialList.getName(), jqbzMaterialList.getNum()*-1);

                 //根据任务书中的物料名称获取到物料的编码
                 CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterial.getResourcename());
                 if (!AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                     throw new AdscmSystemException("找不到该物料编码");
                 }
                 if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getType(),null)){
                     jqbzMaterialList.setType(cgMaterial.getType());
                 }
                 if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial.getBatchnums(),null)){
                     jqbzMaterialList.setBatch(jqylMaterial.getBatchnums());
                 }
                 if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getCode(),null)){
                     //查询今天最大的号
                     if (jqbzMaterialList.getNum()>1){
                         throw new AdscmSystemException("数量大于1不能生成物料编码");
                     }
                     String yearMonth = new SimpleDateFormat("yyMMdd").format(new Date());
                     String code=cgMaterial.getCode().trim()+yearMonth;
                     Wrapper<JqbzMaterialList> wrapper =new EntityWrapper<>();
                     wrapper.like("code",code, SqlLike.RIGHT);
                     wrapper.orderBy("code",false);
                     List<JqbzMaterialList> jqbzMaterialLists = super.selectList(wrapper);
                     if (jqbzMaterialLists!=null && jqbzMaterialLists.size()>0){
                         JqbzMaterialList jqbzMaterialList1 = jqbzMaterialLists.get(0);
                         code=jqbzMaterialList1.getCode().replace(cgMaterial.getCode().trim(),"");
                         Long tempcode= Long.valueOf(code)+1;
                         jqbzMaterialList.setCode(cgMaterial.getCode().trim()+String.valueOf(tempcode));
                     }else {
                         jqbzMaterialList.setCode(cgMaterial.getCode().trim()+yearMonth+"001");
                     }
                 }
                 //添加用料信息
                 jqbzMaterialList.setCreateTime(new Date());
                 jqbzMaterialList.setCreator(token.getUser().getId().toString());
                 jqbzMaterialList.setState(null);
                 //默认使用时间为当前
                 jqbzMaterialList.setUseTime(new Date());
                 super.insert(jqbzMaterialList);

                 //如果提交的数量和计划的数量相等，默认完成装配
                 JqbzMaterial jqbzMaterial = jqbzMaterialMapper.selectById(jqbzMaterialList.getPid());
                 Wrapper<JqbzMaterialList> getAllWrapper=new EntityWrapper<>();
                 getAllWrapper.eq("pid",jqbzMaterial.getId());
                 getAllWrapper.eq("state","1");
                 List<JqbzMaterialList> jqbzMaterialLists = super.selectList(getAllWrapper);
                 float tempNum=jqbzMaterialList.getNum();;//默认算上当前这条
                 for (JqbzMaterialList materialList : jqbzMaterialLists) {
                     tempNum=tempNum+materialList.getNum();
                 }
                 if (jqbzMaterial.getNum()<tempNum){
                     throw  new AdscmSystemException("添加数量大于了需求数量");
                 }
                 if (jqbzMaterial.getNum()==tempNum){
                     jqbzMaterial.setIsAssembly(1);
                     jqbzMaterialMapper.updateById(jqbzMaterial);
                 }else {
                     jqbzMaterial.setIsAssembly(0);
                     jqbzMaterialMapper.updateById(jqbzMaterial);
                 }
                 //出库信息
                 JqylMaterialdetail jqylMaterialdetail=new JqylMaterialdetail();
                 jqylMaterialdetail.setName(jqylMaterial.getResourcename());
                 jqylMaterialdetail.setTypenums(jqylMaterial.getTypenums());
                 jqylMaterialdetail.setUnit(jqylMaterial.getUnit());
                 jqylMaterialdetail.setBatchnums(jqylMaterial.getBatchnums());
                 //设置这个部件的编码
                 JqbzPartsassembly jqbzPartsassembly = jqbzPartsassemblyMapper.selectById(jqbzMaterial.getTid());
                 if (AdscmBaseUtils.getInstance().isNotEmpty(jqbzPartsassembly,null)){
                     jqylMaterialdetail.setPcode(jqbzPartsassembly.getTaskcode());
                 }
                 jqylMaterialdetail.setOutstorageaddtime(new Date());
                 if (AdscmBaseUtils.getInstance().isNotEmpty(token,null)){
                     jqylMaterialdetail.setUseperson(token.getUser().getId().toString());
                 }else {
                     throw  new AdscmSystemException("请重新登录");
                 }
                 jqylMaterialdetail.setIsrepair(0);
                 jqylMaterialdetail.setUsenums( Double.valueOf(jqbzMaterialList.getNum()) );
                 jqylMaterialdetail.setMaterialstate(jqbzMaterialList.getState());
                 jqylMaterialdetail.setPid(jqbzMaterialList.getId().toString());
                 jqylMaterialdetail.setOutstoragetime(jqbzMaterialList.getUseTime());
                 jqylMaterialdetail.setTid(jqylMaterial.getTid().toString());
                 jqylMaterialdetail.setCode(jqbzMaterialList.getCode());
                 jqylMaterialdetail.setMaterialstate("1");
                 jqylMaterialdetailMapper.insert(jqylMaterialdetail);
                 //生成检验记录
                 Wrapper<JqylSettingMaterialCheck> wrapper =new EntityWrapper<>();
                 wrapper.eq("pid",cgMaterial.getId());
                 wrapper.eq("isEnable",1);

                 List<JqylSettingMaterialCheck> jqylSettingMaterialChecks = jqylSettingMaterialCheckMapper.selectList(wrapper);

                 if (jqylSettingMaterialChecks!=null && jqylSettingMaterialChecks.size()>0 ){
                     for (JqylSettingMaterialCheck jqylSettingMaterialCheck : jqylSettingMaterialChecks) {
                         JqbzMaterialListCheck  jqbzMaterialListCheck =new JqbzMaterialListCheck();
                         jqbzMaterialListCheck.setPid(jqbzMaterialList.getId());
                         jqbzMaterialListCheck.setCid(jqylSettingMaterialCheck.getId());
                         jqbzMaterialListCheck.setName(jqylSettingMaterialCheck.getName());
                         jqbzMaterialListCheck.setReference(jqylSettingMaterialCheck.getReference());
                         jqbzMaterialListCheck.setType(jqylSettingMaterialCheck.getType());
                         jqbzMaterialListCheck.setUnit(jqylSettingMaterialCheck.getUnit());
                         jqbzMaterialListCheck.setRemark(jqylSettingMaterialCheck.getRemark());
                         jqbzMaterialListCheck.setRank(jqylSettingMaterialCheck.getRank());
                         jqbzMaterialListCheckMapper.insert(jqbzMaterialListCheck);
                     }
                     jqbzMaterialList.setIsCheck(1);
                 }else {
                     jqbzMaterialList.setIsCheck(0);
                     jqbzMaterialList.setState("1");
                 }
                 super.updateById(jqbzMaterialList);
             }
         }





        return false;
    }

     @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateJqbzMaterialList(JqbzMaterialList jqbzMaterialList) throws AdscmSystemException{
         if (AdscmBaseUtils.getInstance().isNotEmpty(jqbzMaterialList.getCode(),null)){
             if (jqbzMaterialList.getNum()>1){
                 throw  new AdscmSystemException("无法修改数量");
             }
         }
         Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
         wrapper.eq("pid",jqbzMaterialList.getId());
         List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
         JqylMaterialdetail jqylMaterialdetail =null;
         if (jqylMaterialdetails!=null &&jqylMaterialdetails.size()>0){
             jqylMaterialdetail=jqylMaterialdetails.get(0);
         }
         JqbzMaterialList oldjqbzMaterialList = super.selectById(jqbzMaterialList.getId());
         Float num=  oldjqbzMaterialList.getNum()-jqbzMaterialList.getNum();
         //数量有变化修改原料库  库存
         if (num!=0){
             jqylMaterialService.updateJqylMaterialyValue(jqbzMaterialList.getName(), num);
         }
         //修改原料的出库记录 数量和状态
         jqylMaterialdetail.setMaterialstate(jqbzMaterialList.getState());
         jqylMaterialdetail.setUsenums(Double.valueOf(jqbzMaterialList.getNum().toString()));
         jqylMaterialdetailMapper.updateById(jqylMaterialdetail);

        boolean b = super.updateById(jqbzMaterialList);
        return b;
    }

    @Override
    public List<JqbzMaterialList> selectByTid(String pid) {
         Wrapper<JqbzMaterialList> wrapper =new EntityWrapper<>();
        wrapper.eq("pid",pid);
        List<JqbzMaterialList> jqbzMaterialLists = super.selectList(wrapper);
        for (JqbzMaterialList jqbzMaterialList : jqbzMaterialLists) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqbzMaterialList.getName(),null)){
                JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(Integer.valueOf(jqbzMaterialList.getName()));
                CgMaterial cgMaterial = cgMaterialMapper.selectById(Integer.valueOf(jqylMaterial.getResourcename()));
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    jqbzMaterialList.setNameName(cgMaterial.getName());
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqbzMaterialList.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqbzMaterialList.getCreator());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                    jqbzMaterialList.setCreatorName(jyUser.getName());
                }
            }

        }
        return jqbzMaterialLists;
    }

    @Override
    public List<JqylMaterial> queryMaterial( String id)throws  AdscmSystemException {
        Wrapper<JqylMaterial> wrapper =new EntityWrapper<>();
        wrapper.setSqlSelect("TID","RESOURCENAME","TASKCODE","REMAININGNUMS");
        wrapper.eq("ISTASKBEGIN",1);
        wrapper.eq("ISTASKEND",0);
        wrapper.eq("RESOURCENAME",id);
        List<JqylMaterial> jqylMaterials = jqylMaterialMapper.selectList(wrapper);
        if(!(jqylMaterials!=null&&jqylMaterials.size()>0)){
            throw new AdscmSystemException("原料库中无存货");
        }
        for (JqylMaterial jqylMaterial : jqylMaterials) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial.getResourcename(),null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterial.getResourcename());
                jqylMaterial.setCgMaterial(cgMaterial);
            }
        }

        return jqylMaterials;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteJqbzMaterialList(Integer id)throws AdscmSystemException {
         //1.查询出该条记录
        JqbzMaterialList jqbzMaterialList = super.selectById(id);
        //2.修改回原来的库存
        jqylMaterialService.updateJqylMaterialyValue(jqbzMaterialList.getName(), jqbzMaterialList.getNum());
        ///3.删除掉对应的库存出库记录
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("PID",id);
        List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
        if (jqylMaterialdetails!=null&& jqylMaterialdetails.size()>0){
            JqylMaterialdetail jqylMaterialdetail = jqylMaterialdetails.get(0);
            jqylMaterialdetailMapper.deleteById(jqylMaterialdetail.getId());
        }
        //删除对应的检验记录
         Wrapper<JqbzMaterialListCheck> jqbzMaterialListCheckwrapper=new EntityWrapper<>();
        jqbzMaterialListCheckwrapper.eq("pid",id);
        List<JqbzMaterialListCheck> jqbzMaterialListChecks = jqbzMaterialListCheckMapper.selectList(jqbzMaterialListCheckwrapper);
        if (jqbzMaterialListChecks!=null && jqbzMaterialListChecks.size()>0){
            for (JqbzMaterialListCheck jqbzMaterialListCheck : jqbzMaterialListChecks) {
                jqbzMaterialListCheckMapper.deleteById(jqbzMaterialListCheck);
            }
        }
        //查询现在这个父级记录，设置他装配状态为未装配
        JqbzMaterial jqbzMaterial = jqbzMaterialMapper.selectById(jqbzMaterialList.getPid());
        jqbzMaterial.setIsAssembly(0);
        jqbzMaterialMapper.updateById(jqbzMaterial);
        boolean b = super.deleteById(id);
        return b;
    }
}
